<template>
	<view>
		<view class="cu-load load-modal" v-if="isMask">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<image src="/static/logo.png" mode="aspectFit"></image>
			<view class="gray-text">第{{uploadIndex+1}}个文件上传中...{{uploadProgress}}% </view>
		</view>
		
		<!-- 导航栏 -->
		<cu-custom bgColor="bg-gradual-red" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">媒体资源上传</block>
		</cu-custom>
		
		<!-- 为H5准备文件选择器器 -->
		<!-- #ifdef H5 -->
			<view style="display: none;" ref="input" ></view>
		<!-- #endif -->
		
		<form :disabled="isMask">
			<view class="cu-form-group margin-top-sm">
				<view class="title text-bold">文件标题</view>
				<input class="" placeholder="请输入文件标题" name="fileTitle" v-model="fileTitle"></input>
			</view>
			<view class="cu-form-group">
				<view class="title text-bold">共享类型</view>
				<!-- <picker @change="pickerChange" :value="fileNatureIndex" :range="fileNatures" range-key="name">
					<view class="picker" style="text-align: left;">
						{{fileNatureName}}
					</view>
				</picker> -->
				<radio-group class="block flex1 fontsmallsize" @change="fileNatureChange">
					<label class="radio margin-right-sm" v-for="(item,index) in fileNatures" :key="item.id"><radio :class="item.id==fileNature?'checked':''" class="margin-right-xs" name="fileNature" :value="item.id" />{{item.name.length>4?item.name.substr(0,4):item.name}}</label>
				</radio-group>
			</view>
			<view class="cu-form-group">
				<view class="title text-bold">文件种类</view>
				<!-- <picker mode="selector" :range="fileTypes" :value="fileTypeIndex" @change="fileTypeChange" range-key="name">
					<view class="picker" style="text-align: left;">{{fileTypeName}}</view>
				</picker> -->
				<radio-group class="block flex1 fontsmallsize" @change="fileTypeChange">
					<label class="radio margin-right-sm" v-for="(item,index) in fileTypes" :key="item.id"><radio :class="item.id==fileType?'checked':''" class="margin-right-xs" name="fileType" :value="item.id"  />{{item.name.length>4?'文档':item.name}}</label>
				</radio-group>
			</view>
			<view class="cu-form-group align-start margin-top-xs">
				<view class="title text-bold">文件说明</view>
				<textarea v-model="fileRemark" maxlength="-1"  placeholder="请输入文件详细说明"></textarea>
			</view>
			<view class="cu-bar bg-white margin-top-xs">
				<view class="action text-bold">上传文件</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" :data-url="imgList[index]">
						<image src="../../static/file.jpg" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="padding flex flex-direction">
				<button class="cu-btn bg-purple lg" @tap="to_save" :disabled="isMask">提交</button>
				<!-- <button class="cu-btn bg-red margin-tb-sm lg">嫣红</button> -->
			</view>
			<!-- #ifndef H5 -->
			<tki-file-manager ref="filemanager" @result="resultPath"></tki-file-manager>
			<!-- #endif -->
		</form>
	</view>
</template>

<script>
	import tkiFileManager from "@/components/tki-file-manager/tki-file-manager.vue";
	export default {
		components:{ tkiFileManager },
		computed:{
			userName(){
				return this.$store.state.userName;
			},
			pwd(){
				return this.$store.state.pwd;
			},
			hasLogin(){
				return this.$store.state.hasLogin;
			},
			fileNatureName(){
				return this.fileNatureIndex>-1?this.fileNatures[this.fileNatureIndex].name:'--请选择--';
			},
			fileTypeName(){
				return this.fileTypeIndex>-1?this.fileTypes[this.fileTypeIndex].name:'--请选择--';
			},
			server(){
				return this.$store.state.server;
			}
		},
		data() {
			return {
				uploadIndex:0,
				uploadProgress:0,
				isMask: false,
				fileInput : null,
				preIndex:0,
				id:null,
				file2:null,
				fileTitle:'',
				fileNature:'',
				fileType:'',
				fileRemark:'',
				fileNatures:[{id:0,name:'--请选择--'}],
				fileNatureIndex:0,
				fileTypes:[{id:0,name:'--请选择--'}],
				fileTypeIndex:0,
				imgList:[]
			}
		},
		methods: {
			pickerChange(e){
				this.fileNatureIndex=e.detail.value;
				this.fileNature=this.fileNatures[this.fileNatureIndex].id;
			},
			fileNatureChange(e){
				this.fileNature=e.detail.value;
			},
			fileTypeChange(e){
				// this.fileType=e.detail.value;
				// this.fileType=this.fileTypes[this.fileTypeIndex].id;
				this.fileType=e.detail.value;
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '对话框',
					content: '确定要删除这张图片吗？',
					cancelText: '退出',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			ChooseImage() {
				// #ifdef H5
					this.fileInput.click();
				// #endif
				
				// #ifndef H5
					this.$refs.filemanager._openFile()
			
				// #endif
			},
			// end_ChooseImage
			resultPath(e){
				if(e){
					var path='file://'+e;
					console.log(e);
					var s= e.split('/');
					var fileName=s[s.length-1];
					console.log(fileName);
					this.imgList.push({src:path,fileName:fileName});
				}else{
					uni.showModal({
						title: '警告',
						content: '通过非系统原生的【文件管理】来选择文件的操作无效！',
						showCancel: false
					});
				}
			},
			to_save(){
				// 先对数据进行校验
				if(!this.fileTitle){
					uni.showModal({
						title: '警告',
						content: '文件标题不能为空',
						showCancel: false
					});
					return;
				}
				/* if(this.fileNatureIndex<1){
					uni.showModal({
						title: '警告',
						content: '共享类型没有选择',
						showCancel: false
					});
					return;
				}
				if(this.fileTypeIndex<1){
					uni.showModal({
						title: '警告',
						content: '文件类型没有选择',
						showCancel: false
					});
					return;
				} */
				if(this.imgList.length<1){
					uni.showModal({
							title: '警告',
							content: '最少要选择一个上传文件',
							showCancel: false
						});
						return;
				}
				var serverUrl=this.server.url;
				this.uploadIndex=0;
				// uni.showLoading({
				// 	title: '上传中...',
				// 	mask: true
				// });
				this.uploadIndex=0;
				this.uploadProgress=0;
				this.isMask=true;
				this.imgList.map((item,index)=>{

					/* 因为要上传大文件,h5和android要区别对待 */
					
					// #ifdef H5
					var formData={
							id:this.id,
							userName:this.userName,
							pwd:this.pwd,
							fileTitle:this.fileTitle,
							fileRemark:this.fileRemark,
							fileNature:this.fileNature,
							fileType:this.fileType,
							fileName:item.fileName
					};
					//console.log(formData);
					var uploadTask= uni.uploadFile({
						url: serverUrl + 'app/save', 
						filePath:item.src,
						name:'file2',
						formData: formData,
						fail:()=>{
							uni.showToast({
								title: '第'+this.uploadIndex+'个文件上传失败',
								icon: 'none'
							});
						},
						complete: () => {
							this.uploadIndex++;
							if(this.uploadIndex==this.imgList.length){
								this.isMask=false;
								this.uploadIndex=0;
								this.uploadProgress=0;
								uni.showModal({
									title: '提示',
									content: '文件上传完成',
									showCancel: false,
									success: (res) => {
										if(res.confirm){
											uni.navigateBack();
										}
									}
									
								});
							}
						}
					});
					uploadTask.onProgressUpdate(res=>{
						this.uploadProgress=res.progress;
					})
					// #endif
					
					// #ifndef H5
					var task = plus.uploader.createUpload(  this.server.url+ "app/save",
						{	
							method:'POST',
							chunkSize:1024 // 文件分块上传，2M每块 
						}, ( t, status )=> {
						// 上传完成
						var fn=item.fileName;
						this.uploadIndex++;
						if ( status == 200 ) {
							console.log( '第' +this.uploadIndex+"个文件，"+fn+'上传成功' );
						} else {
							console.log(  '第' +this.uploadIndex+"个文件，"+fn+'上传失败' );
						}
						if(this.uploadIndex==this.imgList.length){
							this.isMask=false;
							this.uploadIndex=0;
							this.uploadProgress=0;
							uni.showModal({
								title: '提示',
								content: '文件上传完成',
								showCancel: false,
								success: (res) => {
									if(res.confirm){
										uni.navigateBack();
									}
								}
								
							});
						}
					});
					task.addFile( item.src, {key:"file2"} );
					task.addData( "userName", this.userName );
					task.addData( "pwd",this.pwd);
					task.addData( "fileTitle", this.fileTitle);
					task.addData( "fileRemark", this.fileRemark );
					task.addData( "fileNature", this.fileNature+'');
					task.addData( "fileType", this.fileType+'');
					task.addData( "fileName", item.fileName);
					task.addEventListener( "statechanged", (upload,status)=>{
						//if(status==200){
							var uploadedSize=upload.uploadedSize;
							var totalSize=upload.totalSize;
							var progress=Math.floor(uploadedSize/totalSize*100);
							if(progress>this.uploadProgress){
								this.uploadProgress=progress;
								console.log(this.uploadProgress);
							}
						//}
					}, false );
					task.start();
					// #endif
					
				});
			} 
			// end_toSave
			
		},
		onLoad() {
			if(!this.hasLogin){
				uni.redirectTo({
					url:'./login'
				});
				return;
			}
			
			var serverUrl=this.server.url;
			uni.request({
				url: serverUrl+ 'app/edit',
				method: 'GET',
				sslVerify: false,
				data:{},
				success: res => {
					var result=res.data;
					//this.fileNatures=this.fileNatures.concat(result.fileNatures);
					this.fileNatures=result.fileNatures;
					//this.fileTypes=this.fileTypes.concat(result.fileTypes);
					this.fileTypes=result.fileTypes;
					var sysFile=result.sysFile;
					this.id=sysFile.id?sysFile.id:'';
					this.fileTitle=sysFile.fileTitle?sysFile.fileTitle:'';
					this.fileNature=sysFile.fileNature?sysFile.fileNature.id:0;
					this.fileType=sysFile.fileType?sysFile.fileType.id:0;
					this.fileRemark=sysFile.fileRemark?sysFile.fileRemark:'';
					this.fileNatureIndex=this.fileNatures.findIndex(item=>{
						return item.id==this.fileNature;
					});
					this.fileTypeIndex=this.fileTypes.findIndex(item=>{
						return item.id==this.fileType;
					});
				}
			});
			
		},
		mounted() {  
			var input = document.createElement('input');  
			input.type = 'file';  
			input.onchange = (e) => {  
				if(e.target.files.length>0){
					var file=e.target.files[0];
					//console.log(file);
					var src=getObjectURL(file);
					var filename=file.name;
					this.imgList.push({src:src,fileName:filename});
				}
			}  
			this.$refs.input.$el.appendChild(input);
			this.fileInput=input; 
		}  
	}
	
	function getObjectURL(file) {
		var url = null ;
		if (window.createObjectURL!=undefined) { // basic
			url = window.createObjectURL(file) ;
		} else if (window.URL!=undefined) { // mozilla(firefox)
			url = window.URL.createObjectURL(file) ;
		} else if (window.webkitURL!=undefined) { // webkit or chrome
			url = window.webkitURL.createObjectURL(file) ;
		}
		return url ;
	}
</script>

<style>
 .flex1 {
	 flex:1;
 }
 .fontsmallsize {
	 font-size: 13px;
 }
</style>
